from flask import Blueprint, jsonify, request, g
from app.err_no import errno_no
from loguru import logger
import json
import traceback
from app.db.mongoClient import MongoError
from app.db import dbDishQuery

blueprint = Blueprint('dish_query', __name__, url_prefix='/api/dish')


@blueprint.route('/v1/query_all_class', methods=['POST'])
def query_all_class():
    '''
    查询档口所有菜品类别
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        classList = dbDishQuery.queryAllClass(diningNo, stallNo)
        return jsonify(errno_no.OK.data({'classList': classList}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/query_dishes', methods=['POST'])
def query_dishes():
    '''
    查询档口菜品基础信息
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishState = j_data.get('dishState') # "未通过/通过/待审核（fail/pass/stay）, all=全部"
        meunName = j_data.get('meunName')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishState is None or len(dishState) <= 0 \
            or meunName is None or len(meunName) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        dishList = dbDishQuery.queryDishes(diningNo, stallNo, dishState, meunName)

        return jsonify(errno_no.OK.data({'dishList': dishList}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/query_batch_dishes', methods=['POST'])
def query_batch_dishes():
    '''
    组合查询档口菜品基础信息
    "diningNos": ["餐厅Id1", "餐厅Id2", "..."], // 必填字段，不可为空
	// 当stallNos=[]时，只根据diningNo字段查询, 即查询该用户关联的所有餐厅所有档口的菜品
	// 当stallNos=["档口Id1", "档口Id2", ...]时，只根据stallNos查询，即查询档口组合
	"stallNos": ["档口Id1", "档口Id2", ...],  // 必填字段，可为空
	"dishState": "未通过/通过/待审核（fail/pass/stay）, all=全部",  // 必填字段，不可为空
	"meunName": "早餐/午餐/晚餐/夜宵/全部" // 必填字段，不可为空
    '''
    try:
        j_data = json.loads(request.data)
        diningNos = j_data.get('diningNos')
        stallNos = j_data.get('stallNos')
        dishState = j_data.get('dishState') # "未通过/通过/待审核（fail/pass/stay）, all=全部"
        meunName = j_data.get('meunName') # "早餐/午餐/晚餐/夜宵/全部" // 必填字段，不可为空
        startPage = j_data.get('startPage')
        pageSize = j_data.get('pageSize')
        if diningNos is None \
            or stallNos is None \
            or dishState is None or len(dishState) <= 0 \
            or meunName is None or len(meunName) <= 0 \
            or startPage is None or isinstance(startPage, int) is False \
            or pageSize is None or isinstance(pageSize, int) is False or pageSize == 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        totalPages, totalCount, dishList = dbDishQuery.queryBatchDishes(g.userType, diningNos, 
                                stallNos, dishState, meunName, startPage, pageSize)

        data = {
            'totalPages': totalPages,
            'currentPage': startPage,
            'totalCount': totalCount,
            'dishList': dishList
        }
        return jsonify(errno_no.OK.data(data))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/query_dishes_fstImg', methods=['POST'])
def query_dishes_fstImg():
    '''
    获取菜品封面图
    '''
    try:
        j_data = json.loads(request.data)
        imageId = j_data.get('imageId')
        if imageId is None or len(imageId) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDishQuery.queryDishesFstImg(imageId)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(res))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/query_menu_dishes', methods=['POST'])
def query_menu_dishes():
    '''
    查询档口指定餐次菜品信息
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        menuName = j_data.get('menuName')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or menuName is None or len(menuName) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        dishList = dbDishQuery.queryMenuDishes(diningNo, stallNo, menuName)

        return jsonify(errno_no.OK.data({'dishList': dishList}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/query_Img/<imageId>', methods=['GET'])
def query_Img(imageId):
    '''
    获取菜品封面图
    '''
    try:
        res = dbDishQuery.query_Img(imageId)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))
            
        return res
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    
    
@blueprint.route('/v1/query_passed_class', methods=['POST'])
def query_passed_class():
    '''
    查询档口所有审核已经通过的菜品的类别
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        classList = dbDishQuery.query_passed_class(diningNo, stallNo)
        return jsonify(errno_no.OK.data({'classList': classList}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))